import React, { useState, useEffect } from 'react';
import { Table, Checkbox, Input, Modal } from 'antd';
import './index.css';

// 服务项目选项数据
const serviceOptions = [
  {
    id: 'massage-60',
    name: '推拿按摩（60分钟）',
    duration: '60分钟',
    price: '¥268',
    description: '全身放松推拿，缓解肌肉疲劳'
  },
  {
    id: 'acupuncture-60',
    name: '针灸治疗（60分钟）',
    duration: '60分钟',
    price: '¥328',
    description: '专业针灸调理，改善气血循环'
  },
  {
    id: 'moxibustion-60',
    name: '艾灸调理（60分钟）',
    duration: '60分钟',
    price: '¥298',
    description: '温热艾灸，驱寒除湿'
  },
  {
    id: 'cupping-45',
    name: '拔罐疗法（45分钟）',
    duration: '45分钟',
    price: '¥198',
    description: '传统拔罐，疏通经络'
  },
  {
    id: 'scraping-30',
    name: '经络刮痧（30分钟）',
    duration: '30分钟',
    price: '¥168',
    description: '专业刮痧，排毒养颜'
  },
  {
    id: 'foot-massage-45',
    name: '足部按摩（45分钟）',
    duration: '45分钟',
    price: '¥188',
    description: '足部反射区按摩，改善睡眠'
  },
  {
    id: 'back-massage-30',
    name: '背部理疗（30分钟）',
    duration: '30分钟',
    price: '¥158',
    description: '背部专项调理，缓解肩颈不适'
  },
  {
    id: 'health-consult-30',
    name: '健康咨询（30分钟）',
    duration: '30分钟',
    price: '¥98',
    description: '专业医师健康指导，定制调理方案'
  }
];

// 生成日期范围
const generateDateRange = (days = 7) => {
  const dates = [];
  const now = new Date();
  const weekdays = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];

  for (let i = 0; i < days; i++) {
    const date = new Date(now);
    date.setDate(now.getDate() + i);

    dates.push({
      dateObj: date,
      dayOfWeek: weekdays[date.getDay()],
      month: date.getMonth() + 1,
      day: date.getDate(),
      isToday: i === 0,
      isCalendarIcon: false
    });
  }

  return dates;
};

// 格式化日期显示
const formatDateDisplay = (date) => {
  const options = { year: 'numeric', month: 'long', day: 'numeric', weekday: 'long' };
  return date.toLocaleDateString('zh-CN', options);
};

// 辅助函数：获取姓氏 + 先生/女士
const formatClientName = (fullName, gender) => {
  if (!fullName) return '';
  const lastName = fullName.charAt(0); // 获取姓氏
  return `${lastName}${gender === 'female' ? '女士' : '先生'}`;
};

function Subscribe() {
  // 状态管理
  const [dates, setDates] = useState([]);
  const [selectedDate, setSelectedDate] = useState(null); // 存储选中的普通日期
  const [currentDisplayDate, setCurrentDisplayDate] = useState('');
  const [appointments, setAppointments] = useState([]);
  const [currentAppointmentId, setCurrentAppointmentId] = useState(null);
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [isDetailModalOpen, setIsDetailModalOpen] = useState(false);
  const [isCancelModalOpen, setIsCancelModalOpen] = useState(false);
  const [modalType, setModalType] = useState('edit'); // 只保留编辑模式
  const [cancelReason, setCancelReason] = useState('');
  const [formData, setFormData] = useState({
    clientName: '',
    appointmentDateTime: '',
    serviceType: '',
    appointmentStatus: 'confirmed',
    appointmentNotes: '',
    paymentMethod: 'unpaid',
    selectedServices: [],
    serviceSearch: ''
  });
  const [detailData, setDetailData] = useState(null);
  const [formSubmitted, setFormSubmitted] = useState(false);
  const [currentPage, setCurrentPage] = useState(1);
  const [pageSize, setPageSize] = useState(5);
  const [isCalendarSelected, setIsCalendarSelected] = useState(false); // 日历图标选中状态

  // 初始化数据
  useEffect(() => {
    const dateRange = generateDateRange();
    // 添加日历图标对应的虚拟日期对象
    const calendarIconDate = {
      id: 'custom-calendar',
      name: '日历',
      isCalendarIcon: true
    };
    // 合并普通日期和日历图标
    const allDates = [...dateRange, calendarIconDate];
    setDates(allDates);
    setSelectedDate(dateRange[0]);
    setCurrentDisplayDate(formatDateDisplay(dateRange[0].dateObj));

    // 初始化预约数据 - 包含性别信息
    const demoAppointments = [
      {
        id: 'A2023061502',
        time: '11:00 - 12:00',
        client: {
          name: '张华',
          gender: 'male',
          id: 'C2023042',
          phone: '138****5678'
        },
        services: [
          { name: '针灸治疗（60分钟）', price: '¥328' }
        ],
        status: 'ongoing',
        notes: '肩颈不适，需要重点调理'
      },
      {
        id: 'A2023061503',
        time: '14:00 - 15:00',
        client: {
          name: '赵丽',
          gender: 'female',
          id: 'C2023078',
          phone: '139****4567'
        },
        services: [
          { name: '艾灸调理（60分钟）', price: '¥298' }
        ],
        status: 'pending',
        notes: '客户有颈椎病史，需特别注意'
      },
      {
        id: 'A2023061504',
        time: '15:30 - 16:30',
        client: {
          name: '陈杰',
          gender: 'male',
          id: 'C2023015',
          phone: '137****3456'
        },
        services: [
          { name: '拔罐疗法（45分钟）', price: '¥198' }
        ],
        status: 'pending',
        notes: '腰椎不适，要求加强腰部拔罐'
      },
      {
        id: 'A2023061601',
        time: '09:00 - 10:00',
        client: {
          name: '林小红',
          gender: 'female',
          id: 'C2023022',
          phone: '136****2345'
        },
        services: [
          { name: '推拿按摩（60分钟）', price: '¥268' }
        ],
        status: 'pending',
        notes: '常规保养，每周一次'
      },
      {
        id: 'A2023061501',
        time: '09:30 - 10:30',
        client: {
          name: '李明',
          gender: 'male',
          id: 'C2023056',
          phone: '135****1234'
        },
        services: [
          { name: '推拿按摩（60分钟）', price: '¥268' },
          { name: '健康咨询（30分钟）', price: '¥98' }
        ],
        status: 'completed',
        notes: '肩颈疲劳，已缓解'
      }
    ];

    setAppointments(demoAppointments);

    // 设置默认日期时间为今天的9:00
    const today = new Date();
    today.setHours(9, 0, 0, 0);
    const formattedDateTime = today.toISOString().slice(0, 16);
    setFormData(prev => ({
      ...prev,
      appointmentDateTime: formattedDateTime,
      selectedServices: [],
      serviceSearch: ''
    }));
  }, []);

  // 处理普通日期选择
  const handleDateSelect = (date) => {
    setIsCalendarSelected(false);
    setSelectedDate(date);
    const selectedDateStr = formatDateDisplay(date.dateObj);
    setCurrentDisplayDate(selectedDateStr);
  };

  // 处理日历图标选择
  const handleCalendarSelect = () => {
    const newState = !isCalendarSelected;
    setIsCalendarSelected(newState);
    setSelectedDate(null);

    if (newState) {
      setCurrentDisplayDate('全部预约');
    } else {
      const today = dates.find(d => d.isToday);
      if (today) {
        setSelectedDate(today);
        setCurrentDisplayDate(formatDateDisplay(today.dateObj));
      }
    }
  };

  // 关闭模态框
  const closeModal = () => {
    setIsModalOpen(false);
    setIsDetailModalOpen(false);
    setIsCancelModalOpen(false);
    setCurrentAppointmentId(null);
    setCancelReason('');
    setFormSubmitted(false);
  };

  // 处理表单数据变更
  const handleFormChange = (e) => {
    const { name, value } = e.target;
    setFormData(prev => ({ ...prev, [name]: value }));
  };

  // 保存预约
  const handleSaveAppointment = () => {
    setFormSubmitted(true);
    // 简单验证
    if (!formData.clientName.trim()) return;
    if (!formData.selectedServices.length) return;
    if (!formData.appointmentDateTime) return;

    // 更新现有预约
    setAppointments(prev => prev.map(appt => {
      if (appt.id === currentAppointmentId) {
        // 处理多选服务
        const selectedServiceItems = formData.selectedServices.map(serviceId =>
          serviceOptions.find(item => item.id === serviceId)
        ).filter(Boolean);

        // 解析日期时间
        const appointmentDateTime = new Date(formData.appointmentDateTime);
        const startTime = `${appointmentDateTime.getHours().toString().padStart(2, '0')}:${appointmentDateTime.getMinutes().toString().padStart(2, '0')}`;

        // 计算结束时间（默认加1小时）
        const endTimeObj = new Date(appointmentDateTime);
        endTimeObj.setHours(endTimeObj.getHours() + 1);
        const endTime = `${endTimeObj.getHours().toString().padStart(2, '0')}:${endTimeObj.getMinutes().toString().padStart(2, '0')}`;

        return {
          ...appt,
          time: `${startTime} - ${endTime}`,
          client: { ...appt.client, name: formData.clientName },
          services: selectedServiceItems.map(service => ({
            name: service.name,
            price: service.price
          })),
          notes: formData.appointmentNotes
        };
      }
      return appt;
    }));
    alert('预约已成功更新');
    closeModal();
  };

  // 查看详情 - 点击行时调用
  const handleViewDetail = (record) => {
    setDetailData(record);
    setIsDetailModalOpen(true);
  };

  // 编辑预约
  const handleEditAppointment = (id) => {
    const appointment = appointments.find(appt => appt.id === id);
    if (appointment) {
      setCurrentAppointmentId(id);
      setModalType('edit');
      setFormSubmitted(false);

      // 映射服务到表单选择
      const serviceIds = appointment.services.map(service => {
        const match = serviceOptions.find(opt => opt.name === service.name);
        return match ? match.id : null;
      }).filter(Boolean);

      // 解析开始时间
      const startTime = appointment.time.split(' - ')[0];

      // 组合日期和时间
      const dateObj = new Date(selectedDate?.dateObj || new Date());
      const [hours, minutes] = startTime.split(':').map(Number);
      dateObj.setHours(hours, minutes);
      const formattedDateTime = dateObj.toISOString().slice(0, 16);

      setFormData({
        clientName: appointment.client.name,
        appointmentDateTime: formattedDateTime,
        serviceType: '',
        appointmentStatus: appointment.status === 'pending' ? 'confirmed' : appointment.status,
        appointmentNotes: appointment.notes,
        paymentMethod: 'unpaid',
        selectedServices: serviceIds,
        serviceSearch: ''
      });

      setIsModalOpen(true);
    }
  };

  // 完成预约
  const handleCompleteAppointment = (id) => {
    setCurrentAppointmentId(id);
    setAppointments(prev => prev.map(appt =>
      appt.id === id ? { ...appt, status: 'completed' } : appt
    ));
    alert('已标记预约为完成');
  };

  // 处理分页变化
  const handleTableChange = (pagination) => {
    setCurrentPage(pagination.current);
    setPageSize(pagination.pageSize);
  };

  // 预约列表表格列配置 - 优化字体大小和客户信息显示
  const appointmentColumns = [
    {
      title: <span style={{ fontSize: '18px', fontWeight: 'bold' }}>预约时间</span>,
      dataIndex: 'time',
      key: 'time',
      width: 200,
      render: (time, record) => (
        <div className="timeInfo">
          <div style={{ fontSize: '20px', fontWeight: '500' }}>{time}</div>
          <div className="appointmentId">预约号: {record.id}</div>
        </div>
      ),
    },
    {
      title: <span style={{ fontSize: '18px', fontWeight: 'bold' }}>客户姓名</span>,
      dataIndex: 'client',
      key: 'client',
      width: 200,
      render: (client) => (
        <div className="clientInfo" style={{ display: 'flex', alignItems: 'center' }}>
          {/* 统一头像图标颜色为深绿色系 */}
          <div style={{ 
            width: '60px', 
            height: '60px', 
            borderRadius: '50%', 
            backgroundColor: '#E8F5E9', // 浅绿色背景
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            fontSize: '24px',
            color: '#2E7D32' // 深绿色图标
          }}>
            <i className="fa fa-user"></i>
          </div>
          <div style={{ marginLeft: '15px' }}>
            {/* 显示姓氏+先生/女士 */}
            <div className="clientName" style={{ fontSize: '20px' }}>
              {formatClientName(client.name, client.gender)}
            </div>
          </div>
        </div>
      ),
    },
    {
      title: <span style={{ fontSize: '18px', fontWeight: 'bold' }}>服务项目</span>,
      dataIndex: 'services',
      key: 'services',
      width: 300,
      render: (services) => (
        <div>
          {services.map((service, index) => (
            <div key={index} style={{ fontSize: '20px', marginBottom: '8px' }}>
              {service.name}
            </div>
          ))}
        </div>
      ),
    },
    {
      title: <span style={{ fontSize: '18px', fontWeight: 'bold' }}>联系电话</span>,
      dataIndex: 'client',
      key: 'phone',
      width: 200,
      render: (client) => (
        <div style={{ fontSize: '20px' }}>{client.phone}</div>
      ),
    },
  ];

  // 服务项目表格列配置
  const serviceColumns = [
    {
      title: (
        <Checkbox
          checked={formData.selectedServices.length === serviceOptions.length && serviceOptions.length > 0}
          onChange={(e) => {
            if (e.target.checked) {
              setFormData(prev => ({
                ...prev,
                selectedServices: serviceOptions.map(item => item.id)
              }));
            } else {
              setFormData(prev => ({ ...prev, selectedServices: [] }));
            }
          }}
        />
      ),
      dataIndex: 'id',
      key: 'select',
      width: 60,
      render: (id) => (
        <Checkbox
          checked={formData.selectedServices.includes(id)}
          onChange={(e) => {
            if (e.target.checked) {
              setFormData(prev => ({
                ...prev,
                selectedServices: [...prev.selectedServices, id]
              }));
            } else {
              setFormData(prev => ({
                ...prev,
                selectedServices: prev.selectedServices.filter(serviceId => serviceId !== id)
              }));
            }
          }}
        />
      ),
    },
    {
      title: <span style={{ fontSize: '16px', fontWeight: 'bold' }}>服务名称</span>,
      dataIndex: 'name',
      key: 'name',
      render: (name) => <span style={{ fontWeight: '500', fontSize: '16px' }}>{name}</span>,
    },
    {
      title: <span style={{ fontSize: '16px', fontWeight: 'bold' }}>服务时长</span>,
      dataIndex: 'duration',
      key: 'duration',
      width: 120,
      render: (duration) => <span style={{ fontSize: '16px' }}>{duration}</span>,
    },
    {
      title: <span style={{ fontSize: '16px', fontWeight: 'bold' }}>单价</span>,
      dataIndex: 'price',
      key: 'price',
      width: 120,
      render: (price) => <span style={{ color: '#556B2F', fontSize: '16px' }}>{price}</span>,
    },
    {
      title: <span style={{ fontSize: '16px', fontWeight: 'bold' }}>服务说明</span>,
      dataIndex: 'description',
      key: 'description',
      width: 180,
      render: (description) => <span style={{ fontSize: '15px', color: '#666' }}>{description}</span>,
    },
  ];

  // 筛选服务数据
  const filteredServices = serviceOptions.filter(item => {
    if (!formData.serviceSearch) return true;
    const searchStr = formData.serviceSearch.toLowerCase();
    return item.name.toLowerCase().includes(searchStr) ||
      item.description.toLowerCase().includes(searchStr);
  });

  // 根据选中状态筛选显示的预约列表
  const filteredAppointments = isCalendarSelected
    ? appointments // 日历图标选中时显示全部预约
    : selectedDate
      ? appointments.filter(() => {
        // 这里简化处理，实际项目中应根据预约日期过滤
        return true;
      })
      : appointments;

  return (
    <div className='subscribe'>
      <div className="subscribeContainer">
        {/* 页面标题与操作区 */}
        <div className="pageHeader">
          <div className="headerActions">
            <div>
              <h2 className="pageTitle" style={{ fontSize: '32px' }}>预约管理</h2>
              <p className="currentDate" id="currentDisplayDate" style={{ fontSize: '18px' }}>当前显示：{currentDisplayDate}</p>
            </div>

            <div className="headerActionsRight">
              <div className="searchBar" style={{ width: '400px' }}>
                <input
                  type="text"
                  placeholder="搜索账号或预约号"
                  className="searchInput"
                  style={{ fontSize: '18px', height: '48px', paddingLeft: '42px' }}
                />
                <i className="fa fa-search searchIcon" style={{ fontSize: '20px' }}></i>
              </div>
            </div>
          </div>
        </div>

        {/* 日期导航 */}
        <div className="dateNavContainer" id="dateNavigation" style={{ marginBottom: '32px' }}>
          {dates.map((date, index) => {
            // 日历图标项（全部预约）
            if (date.isCalendarIcon) {
              return (
                <div
                  key={date.id}
                  className={`dateNavItem calendarIconItem ${isCalendarSelected ? 'active' : ''}`}
                  onClick={handleCalendarSelect}
                  title={date.name}
                  style={{ minWidth: '100px', minHeight: '90px' }}
                >
                  <i className={`fa fa-calendar-o calendarIcon ${isCalendarSelected ? 'activeIcon' : ''}`} style={{ fontSize: '24px' }}></i>
                </div>
              );
            }

            // 普通日期项
            return (
              <div
                key={index}
                className={`dateNavItem ${!isCalendarSelected && selectedDate?.dateObj?.toDateString() === date.dateObj.toDateString() ? 'active' : ''}`}
                onClick={() => handleDateSelect(date)}
                style={{ minWidth: '100px', minHeight: '90px' }}
              >
                <div className="dateNavDay" style={{ fontSize: '18px' }}>
                  {date.isToday ? '今天' : date.dayOfWeek}
                </div>
                <div className="dateNavDate" style={{ fontSize: '16px' }}>
                  {date.month}/{date.day}
                </div>
              </div>
            );
          })}
        </div>

        {/* 预约列表 - 点击行弹出详情 */}
        <div className="appointmentTableContainer">
          <Table
            columns={appointmentColumns}
            dataSource={filteredAppointments}
            rowKey="id"
            pagination={{
              current: currentPage,
              pageSize: pageSize,
              total: filteredAppointments.length,
              pageSizeOptions: ['5', '10', '20'],
              showSizeChanger: true,
              showTotal: (total) => `共 ${total} 条记录`,
              showQuickJumper: true,
              className: 'antd-pagination',
              size: 'large' // 分页控件放大
            }}
            onChange={handleTableChange}
            className="appointmentTable"
            onRow={(record) => ({
              onClick: () => handleViewDetail(record), // 点击行查看详情
              style: { 
                cursor: 'pointer',
                height: '150px', // 调整行高，使其不太高
                fontSize: '18px',
                padding: '16px'
              }
            })}
            scroll={{ x: 'max-content' }}
          />
        </div>

        {/* 编辑预约模态框 */}
        <Modal
          open={isModalOpen}
          onCancel={closeModal}
          title="修改预约"
          width='60%'
          footer={[
            <button key="cancel" className="cancelModalBtn" onClick={closeModal} style={{ 
              fontSize: '18px', 
              padding: '12px 24px',
              backgroundColor: '#f0f0f0',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer',
              marginRight: '10px'
            }}>
              取消
            </button>,
            <button key="save" className="addBtn" onClick={handleSaveAppointment} style={{ 
              fontSize: '18px', 
              padding: '12px 24px',
              backgroundColor: '#556B2F',
              color: 'white',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer'
            }}>
              保存
            </button>
          ]}
        >
          <div className="modalBody">
            {/* 基础信息区域 */}
            <div className="formGrid mb-6">
              <div className="formGroup">
                <label className="formLabel" style={{ fontSize: '18px' }}>客户信息</label>
                <div className="relative">
                  <input
                    type="text"
                    name="clientName"
                    value={formData.clientName}
                    onChange={handleFormChange}
                    placeholder="输入客户姓名或手机号"
                    className="formInput"
                    style={{ fontSize: '16px', height: '50px' }}
                  />
                  <i className="fa fa-user absolute left-3 top-1/2 transform -translate-y-1/2 text-gray-400" style={{ fontSize: '20px' }}></i>
                </div>
                {!formData.clientName.trim() && formSubmitted && (
                  <span className="errorMsg" style={{ fontSize: '14px' }}>请输入客户信息</span>
                )}
              </div>

              <div className="formGroup">
                <label className="formLabel" style={{ fontSize: '18px' }}>预约日期和时间</label>
                <div className="relative">
                  <input
                    type="datetime-local"
                    name="appointmentDateTime"
                    value={formData.appointmentDateTime}
                    onChange={handleFormChange}
                    className="formInput"
                    min={new Date().toISOString().slice(0, 16)}
                    style={{ fontSize: '16px', height: '50px' }}
                  />
                  <i className="fa fa-calendar absolute right-3 top-1/2 transform -translate-y-1/2 text-gray-400" style={{ fontSize: '20px' }}></i>
                </div>
                {!formData.appointmentDateTime && formSubmitted && (
                  <span className="errorMsg" style={{ fontSize: '14px' }}>请选择预约日期和时间</span>
                )}
              </div>
            </div>

            {/* 服务项目多选表格区域 */}
            <div className="mb-6">
              <div className="flex justify-between items-center mb-4">
                <label className="formLabel font-medium" style={{ fontSize: '18px' }}>服务项目选择 <span className="text-red-500">*</span></label>
                <div className="searchBar" style={{ width: '320px' }}>
                  <Input
                    placeholder="搜索服务项目..."
                    value={formData.serviceSearch}
                    onChange={(e) => setFormData(prev => ({ ...prev, serviceSearch: e.target.value }))}
                    className="formInput"
                    style={{ fontSize: '16px', height: '50px' }}
                  />
                  <i className="fa fa-search searchIcon" style={{ fontSize: '20px' }}></i>
                </div>
              </div>

              {/* 多选表格 */}
              <div className="tableContainer" style={{ maxHeight: '360px', overflowY: 'auto', border: '1px solid #eee', borderRadius: '6px' }}>
                <Table
                  columns={serviceColumns}
                  dataSource={filteredServices}
                  rowKey="id"
                  pagination={false}
                  showHeader={true}
                  className="serviceTable"
                  onRow={() => ({
                    style: { height: '70px' }
                  })}
                />

                {filteredServices.length === 0 && (
                  <div style={{ padding: '30px', textAlign: 'center', color: '#999', fontSize: '16px' }}>
                    <i className="fa fa-search-minus mr-2" style={{ fontSize: '20px' }}></i>未找到匹配的服务项目
                  </div>
                )}
              </div>

              {/* 已选服务汇总 */}
              {formData.selectedServices.length > 0 && (
                <div className="selectedServicesSummary mt-4 p-4 bg-f9f9f9 rounded-lg">
                  <h4 className="text-sm font-medium mb-2" style={{ fontSize: '16px' }}>已选服务 ({formData.selectedServices.length}项)</h4>
                  <div className="flex flex-wrap gap-2">
                    {formData.selectedServices.map(serviceId => {
                      const service = serviceOptions.find(item => item.id === serviceId);
                      return service ? (
                        <span key={serviceId} className="inline-flex items-center px-3 py-1 bg-white border border-gray-200 rounded-full text-sm" style={{ fontSize: '15px' }}>
                          {service.name}
                          <button
                            className="ml-1 text-gray-400 hover:text-red-500"
                            onClick={() => setFormData(prev => ({
                              ...prev,
                              selectedServices: prev.selectedServices.filter(id => id !== serviceId)
                            }))}
                          >
                            <i className="fa fa-times"></i>
                          </button>
                        </span>
                      ) : null;
                    })}
                  </div>
                  <div className="mt-3 text-right">
                    <span className="font-medium" style={{ fontSize: '16px' }}>合计金额: </span>
                    <span className="text-primary font-bold" style={{ fontSize: '18px' }}>
                      ¥{formData.selectedServices.reduce((total, serviceId) => {
                        const service = serviceOptions.find(item => item.id === serviceId);
                        return service ? total + parseInt(service.price.replace('¥', '')) : total;
                      }, 0)}
                    </span>
                  </div>
                </div>
              )}

              {!formData.selectedServices.length && formSubmitted && (
                <span className="errorMsg" style={{ fontSize: '14px' }}>请至少选择一项服务项目</span>
              )}
            </div>

            {/* 其他信息区域 */}
            <div className="formGroup mb-4">
              <label className="formLabel" style={{ fontSize: '18px' }}>客户健康状况/备注</label>
              <textarea
                name="appointmentNotes"
                value={formData.appointmentNotes}
                onChange={handleFormChange}
                rows="3"
                placeholder="请输入客户健康状况、特殊需求等信息..."
                className="formTextarea"
                style={{ fontSize: '16px' }}
              ></textarea>
            </div>
          </div>
        </Modal>

        {/* 预约详情弹窗 - 简化版，页面中心显示 */}
        <Modal
          open={isDetailModalOpen}
          onCancel={closeModal}
          title="预约详情"
          footer={[
            <button key="close" className="addBtn" onClick={closeModal} style={{ 
              fontSize: '18px', 
              padding: '12px 24px',
              backgroundColor: '#556B2F',
              color: 'white',
              border: 'none',
              borderRadius: '6px',
              cursor: 'pointer'
            }}>
              关闭
            </button>
          ]}
          centered // 页面中心弹出
          width={600} // 控制弹窗宽度
        >
          {detailData && (
            <div className="modalBody">
              <div className="formGrid">
                <div style={{ width: '100%' }}>
                  <div className="bg-light rounded-lg p-6">
                    <div className="flex justify-between mb-4">
                      <span className="text-gray-600" style={{ fontSize: '18px' }}>预约时间</span>
                      <span style={{ fontSize: '20px', fontWeight: 'bold' }}>
                        {currentDisplayDate.split(' ')[0]} {detailData.time}
                      </span>
                    </div>
                    
                    <div className="flex justify-between mb-4">
                      <span className="text-gray-600" style={{ fontSize: '18px' }}>客户姓名</span>
                      <span style={{ fontSize: '20px' }}>
                        {formatClientName(detailData.client.name, detailData.client.gender)}
                      </span>
                    </div>
                    
                    <div className="flex justify-between mb-4">
                      <span className="text-gray-600" style={{ fontSize: '18px' }}>预约项目</span>
                      <span style={{ fontSize: '20px' }}>
                        {detailData.services.map(s => s.name).join('、')}
                      </span>
                    </div>
                    
                    <div className="flex justify-between mb-4">
                      <span className="text-gray-600" style={{ fontSize: '18px' }}>联系电话</span>
                      <span style={{ fontSize: '20px' }}>{detailData.client.phone}</span>
                    </div>
                    
                    <div className="flex justify-between">
                      <span className="text-gray-600" style={{ fontSize: '18px' }}>状态</span>
                      <span className={`font-medium ${
                        detailData.status === 'pending' ? 'text-yellow-600' : 
                        detailData.status === 'ongoing' ? 'text-blue-600' : 
                        detailData.status === 'completed' ? 'text-green-600' : 'text-red-600'
                      }`} style={{ fontSize: '20px' }}>
                        {detailData.status === 'pending' || detailData.status === 'ongoing' ? '已安排' : '未安排'}
                      </span>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          )}
        </Modal>
      </div>
    </div>
  );
}

export default Subscribe;
    